package com.zp.resource.user;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.sun.jersey.spi.resource.Singleton;
import com.zp.bean.common.ResultCommonVo;
import com.zp.bean.user.PermissionVo;
import com.zp.bean.user.ResultPermissionVo;
import com.zp.bean.user.ResultRoleVo;
import com.zp.domain.Permission;
import com.zp.domain.Role;
import com.zp.domain.RolePermission;
import com.zp.resource.common.BaseServices;
import com.zp.util.Constant;
import com.zp.util.MyException;

/**
 * role services
 * 
 * @author chenlijun08@gmail.com
 * 
 * @version 1.0
 * 
 * @date 2014/2/12
 * 
 */
@Component
@Path("/rest/role")
@Singleton
public class RoleServices extends BaseServices {
	/**
	 * add role path:/role/addRole http:POST
	 * 
	 * @param role
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1}
	 */
	@POST
	@Path("/addRole")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response addRole(Role role) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			this.jpaDao.save(role);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * update Role information path:/role/updateRole Http:PUT
	 * 
	 * @param role
	 * 
	 * @return Response, ResultRoleVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1}
	 */
	@PUT
	@Path("/updateRole")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateRole(Role role) {
		ResultRoleVo result = new ResultRoleVo();
		try {
			this.jpaDao.update(role);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
			result.setRole(role);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * get role by id path:/type/getRole Http:GET
	 * 
	 * @param roleId
	 *            primary key of Role
	 * 
	 * @return Response, ResultRoleVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1,"role":{"id":
	 *         "402881e64458d2bb014458efead00011"
	 *         ,"name":"新闻管理人员","code":"N00001","status":"1"},"list":null}
	 */
	@GET
	@Path("/getRole")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getRoleById(@QueryParam("roleId") String roleId) {
		logger.info("getRoleById called roleId:" + roleId);
		ResultRoleVo result = new ResultRoleVo();
		try {
			Role role = (Role) jpaDao.findById(Role.class, roleId);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
			result.setRole(role);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * delete Role by id path:/role/deleteRole Http:DELETE
	 * 
	 * @param roleId
	 *            primary key of Role
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1}
	 */
	@DELETE
	@Path("/deleteRole")
	@Produces(MediaType.APPLICATION_JSON)
	public Response deleteRole(@QueryParam("roleId") String roleId) {
		logger.info("deleteRole called typeId:" + roleId);
		ResultCommonVo result = new ResultCommonVo();
		try {
			this.jpaDao.deleteById(Role.class, roleId);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * search role with criteria path:/role/searchRole Http:GET
	 * 
	 * @param pageNo
	 * 
	 * @param pageSize
	 * 
	 * @param roleNameorCode
	 *            the name of Role or the code of Role if ignored the value is
	 *            null
	 * 
	 * @return Response, ResultRoleVo with JSON String
	 *         like:{"code":268,"message"
	 *         :"OK","totalCount":4,"role":null,"list":
	 *         [{"id":"402881e64458d2bb014458ef33ab0010"
	 *         ,"name":"系统管理人员","code":"DBA001"
	 *         ,"status":"1"},{"id":"402881e64458d2bb014458f050e50012"
	 *         ,"name":"普通用户","code":"G00001","status":"1"},{"id":
	 *         "402881e64458d2bb014458f0c8920013"
	 *         ,"name":"管理人员","code":"M00001","status"
	 *         :"1"},{"id":"402881e64458d2bb014458efead00011"
	 *         ,"name":"新闻管理人员","code":"N00001","status":"1"}]}
	 */
	@GET
	@Path("/searchRole")
	@Produces(MediaType.APPLICATION_JSON)
	public Response searchRole(@QueryParam("pageNo") int pageNo,
			@QueryParam("pageSize") int pageSize,
			@QueryParam("roleNameorCode") String roleNameorCode) {
		logger.info("searchRole called json pageNo:" + pageNo + " pageSize:"
				+ pageSize + " roleNameorCode:" + roleNameorCode);
		String jpql = "from Role where name=? or code=? order by code asc";
		List<?> list = null;
		ResultRoleVo result = new ResultRoleVo();
		List<Role> lt = new ArrayList<Role>();
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);
		if ("".equals(roleNameorCode) || roleNameorCode == null) {
			jpql = "from Role order by code asc";
			try {
				list = this.jpaDao.getResultData(pageNo, pageSize, jpql, null);
				long totalCount = this.jpaDao.getCount(
						"select count(id) from Role", null);
				result.setTotalCount(totalCount);
			} catch (MyException e) {
				result.setCode(Constant.FAILE_CODE);
				result.setMessage(e.getMessage());
				e.printStackTrace();
			}
		} else {
			Object[] param = { roleNameorCode, roleNameorCode };
			try {
				list = this.jpaDao.getResultData(pageNo, pageSize, jpql, param);
				long totalCount = this.jpaDao.getCount(
						"select count(id) from Role where name=? or code=?",
						param);
				result.setTotalCount(totalCount);
			} catch (MyException e) {
				result.setCode(Constant.FAILE_CODE);
				result.setMessage(e.getMessage());
				e.printStackTrace();
			}
		}
		if (list != null && list.size() > Constant.ZERO) {
			for (Object o : list) {
				Role type = (Role) o;
				lt.add(type);
			}
			result.setList(lt);

		}
		return Response.ok(result).build();

	}

	/**
	 * assign permission to role path:/role/assignPermission Http:POST
	 * 
	 * @param permRole
	 * 
	 * @return Response,ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":1}
	 */
	@POST
	@Path("/assignPermission")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response assignPermissionToRole(RolePermission permRole) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			this.jpaDao.save(permRole);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * get permission from role id path:/role/getPerFromRoleId Http:GET
	 * 
	 * @param roleId
	 *            the primary key of Role
	 * 
	 * @return ResultPermissionVo with JSON String
	 *         like:{"code":268,"message":"OK"
	 *         ,"totalCount":8,"permission":null,"list"
	 *         :[{"id":"402881e6445916b401445921eff30003"
	 *         ,"name":"用户注册","type":{"id"
	 *         :"402881e6445916b40144591eb6580001","name"
	 *         :"权限","code":"AU0001","parentCode"
	 *         :"DA0001"},"parentCode":"P00001"
	 *         ,"url":"/user/registerUser","status"
	 *         :"1","code":"P00002"},{"id":"402881e6445916b401445922cf300004"
	 *         ,"name"
	 *         :"用户登录","type":{"id":"402881e6445916b40144591eb6580001","name"
	 *         :"权限"
	 *         ,"code":"AU0001","parentCode":"DA0001"},"parentCode":"P00001"
	 *         ,"url":"/user/login","status":"1","code":"P00003"}]}
	 */
	@GET
	@Path("/getPerFromRoleId")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getPermissionFromRoleId(@QueryParam("roleId") String roleId) {
		ResultPermissionVo result = new ResultPermissionVo();
		String jpql = "from RolePermission where roleId=?";
		List<?> list = null;
		List<PermissionVo> lt = new ArrayList<PermissionVo>();
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);

		Object[] param = { roleId };
		try {
			list = this.jpaDao.getResultData(Constant.NEGATIVE_ONE,
					Constant.NEGATIVE_ONE, jpql, param);
			long totalCount = this.jpaDao.getCount(
					"select count(id) from RolePermission where roleId=?",
					param);
			result.setTotalCount(totalCount);

			if (list != null && list.size() > Constant.ZERO) {
				for (Object o : list) {
					RolePermission rolePermission = (RolePermission) o;
					Permission permission = (Permission) this.jpaDao.findById(
							Permission.class, rolePermission.getPermissionId());
					PermissionVo vo = new PermissionVo();
					vo.setCode(permission.getCode());
					vo.setId(permission.getId());
					vo.setName(permission.getName());
					vo.setParentCode(permission.getParentCode());
					vo.setStatus(permission.getStatus());
					vo.setType(this.getTypeByCode(permission.getTypeCode()));
					vo.setUrl(permission.getUrl());
					lt.add(vo);
				}
				result.setList(lt);

			}
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}
}
